package com.botarena.server.services.pythonHelpers;

import java.util.ArrayList;
import java.util.List;

import org.python.core.PyBoolean;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.core.PyString;

import com.botarena.shared.BattleTurn;
import com.google.appengine.api.datastore.Key;

public class BattleResultHolder extends PyObject {

	private static final long serialVersionUID = -606526342349190766L;
	
	private final List<BattleTurn> process;
	private final Key bot1Key;
	private final Key bot2Key;
	
	private Key winnerKey;
	private String justification;
	
	public BattleResultHolder(Key bot1Key, Key bot2Key) {
		this.bot1Key = bot1Key;
		this.bot2Key = bot2Key;
		process = new ArrayList<BattleTurn>();
	}

	public void onMove(PyInteger move) {
		process.add(new BattleTurn(move.getValue()));
	}

	public void onTimeLimitExceeded() {
		winnerKey = process.size() % 2 == 1 ? bot1Key : bot2Key;
		justification = "Time limit for move exceeded.";
	}
	
	public void onIllegalMove(PyObject move, PyString detail) {
		winnerKey = process.size() % 2 == 1 ? bot1Key : bot2Key;
		justification = "Illegal move: "+move+". "+detail.asString();
	}
	
	public void onGameEnded(PyBoolean pbdraw) {
		winnerKey = pbdraw.getBooleanValue() ? null : (process.size() % 2 == 1 ? bot1Key : bot2Key);
		justification = pbdraw.getBooleanValue() ? "All fields occupied." : "Five symbols in a row.";
	}
	
	public void onSetParamsException(Object pe, PyInteger number) {
		winnerKey = number.getValue() == 1 ? bot2Key : bot1Key;
		justification = "Uncaught exception on set_params(): "+pe;
	}
	
	public void onException(Object pe) {
		winnerKey = process.size() % 2 == 1 ? bot1Key : bot2Key;
		justification = "Uncaught exception: "+pe;
	}
	
	public String getJustification() {
		return justification;
	}

	public List<BattleTurn> getProcess() {
		return process;
	}

	public Key getWinnerKey() {
		return winnerKey;
	}

	public void bothBotsUnregistered() {
		winnerKey = null;
		justification = "Both opponents failed to register their objects.";
	}

	public void botUnregistered(Key which) {
		winnerKey = which == bot1Key ? bot2Key : bot1Key;
		justification = "One of opponents failed to register its object.";
	}

	public Key getBot2Key() {
		return bot2Key;
	}
	
	public Key getBot1Key() {
		return bot1Key;
	}
}